//
//  BaseViewController.swift
//  Community
//
//  Created by Vampire on 2019/7/18.
//  Copyright © 2019 ZKJ. All rights reserved.
//

import UIKit

class BaseViewController: UIViewController {

    //MARK:自定义导航栏相关
    var isShadow: Bool?{
        didSet{
            if isShadow == true {
                self.navBar?.setShadow(width: MAINWIDTH, bColor: UIColor.clear, sColor: UIColor.hexInt(0xd2d2d2), offset: CGSize(width: 0, height: 5), opacity: 0.3, radius: 2.5)
            }else{
                self.navBar?.setShadow(width: MAINWIDTH, bColor: UIColor.clear, sColor: UIColor.clear, offset: CGSize(width: 0, height: 0), opacity: 0.1, radius: 2.5)
            }
        }
    }
    
    var navBar:UIView?
    var titleLabel:UILabel?
    var backBtn:UIButton?
    var navRightBtn:UIButton?
    var searchTF:UITextField?
    var navTitle: String?{
        didSet{
            self.titleLabel?.text = navTitle
        }
    }
    private var customRightBtnClick: (() -> ())?
    private var customleftBtnClick: (() -> ())?
    private var customSearchAction: ((_ searchStr:String) -> ())?

    //MARK:分页相关
    var page = 1
    var count = 30
    var totalPage = 1

    //MARK:初始化tableView相关
    var tabStyle = 0
    
    lazy var tableView: UITableView = { [unowned self] in
        let tab = UITableView(frame: CGRect.zero, style: self.tabStyle == 0 ? .plain : .grouped)
        tab.delegate = self
        tab.dataSource = self
        tab.backgroundColor = BACKGROUNGCOLOR
        tab.showsVerticalScrollIndicator = false
        tab.showsHorizontalScrollIndicator = false
        tab.tableFooterView = UIView()
        return tab
        }()
    
    //MARK:初始化collectionView相关
    var customLayout = UICollectionViewFlowLayout()
    var colMinLineSpacing: CGFloat?{
        didSet{
            self.customLayout.minimumLineSpacing = colMinLineSpacing ?? 0
        }
    }
    var colMinInteritemSpacing: CGFloat?{
        didSet{
            self.customLayout.minimumInteritemSpacing = colMinInteritemSpacing ?? 0
        }
    }
    lazy var collectionView: UICollectionView = { [unowned self] in
        
        let layout = UICollectionViewFlowLayout()
        self.customLayout = layout
        
        let colV = UICollectionView(frame: CGRect.zero, collectionViewLayout: self.customLayout)
        colV.delegate = self
        colV.dataSource = self
        colV.showsHorizontalScrollIndicator = false
        colV.showsVerticalScrollIndicator = false
        colV.backgroundColor = UIColor.white
        return colV
        }()
    
    //MARK:上下拉头尾
    var mjHeader:MJRefreshNormalHeader = MJRefreshNormalHeader()
    var mjFooter:MJRefreshBackNormalFooter = MJRefreshBackNormalFooter()
    var refreshScrollView:UIScrollView?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white
        self.setCustomNavBar()
    }
    
    //MARK:自定义导航栏
    func setCustomNavBar() {
        
        let height = AllTopNavHeight//CGFloat(kScreenIphoneX ? 88 : 64)
        let navBar = UIView.init(frame: CGRect(x: 0, y: 0, width: MAINWIDTH, height: height))
        navBar.clipsToBounds = false
        navBar.backgroundColor = UIColor.white
        self.view.addSubview(navBar)
        self.view.bringSubviewToFront(navBar)
        self.navBar = navBar
        
        let titleLabel = UILabel.init(frame: CGRect(x: 44, y: StatusBarHeight, width: MAINWIDTH - 88, height: 44))
        titleLabel.font = UIFont.systemFont(ofSize: 17)
        titleLabel.textAlignment = NSTextAlignment.center
//        let color = self == self.navigationController?.viewControllers[0] ? UIColor.black : UIColor.white
        titleLabel.textColor = UIColor.black
        navBar.addSubview(titleLabel)
        self.titleLabel = titleLabel
        
        let backBtn = UIButton.init(frame: CGRect(x: 0, y: StatusBarHeight, width: 44, height: 44))
        backBtn.setImage(UIImage(named: "black_return"), for: UIControl.State.normal)
        backBtn.adjustsImageWhenDisabled = false
        backBtn.adjustsImageWhenHighlighted = false
        backBtn.addTarget(self, action: #selector(backAction), for: UIControl.Event.touchUpInside)
        //第一个页面不放置返回按钮
        if self != self.navigationController?.viewControllers[0] {
            navBar.addSubview(backBtn)
        }
        self.backBtn = backBtn
        
    }
    
    //MARK:返回按钮响应
    @objc func backAction() {
        
        NotificationCenter.default.removeObserver(self)
        self.view.endEditing(true)
        if self == self.navigationController?.viewControllers[0] || self.navigationController == nil {
            self.dismiss(animated: true, completion: nil)
        }else{
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    //MARK:自定义导航栏左键
    /**
     * 自定义导航栏左键
     *
     * - Parameters:
     * - title: title
     * - imageName: imageName
     * - width: btn的宽度  推荐 44 || 66 （两个字至四个字）
     * - customRightBtnClick: btn点击事件
     */
    func addNavLeftButtonWithTitle(title:String, imageName:String, width:CGFloat, customleftBtnClick:(() -> ())?){
        
        self.backBtn?.removeFromSuperview()
        self.customleftBtnClick = customleftBtnClick
        let btn = UIButton.init(type: UIButton.ButtonType.custom)
        btn.frame = CGRect(x: 0, y: StatusBarHeight, width: width, height: 44)
        btn.adjustsImageWhenDisabled = false
        btn.adjustsImageWhenHighlighted = false
        btn.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.left
        btn.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 20, bottom: 0, right: 0)
        btn.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: 10, bottom: 0, right: 0)
        btn.addTarget(self, action: #selector(rightOrLeftOrSearchClick(sender:)), for: UIControl.Event.touchUpInside)
        btn.tag = 1
        if title.count > 0 {
            btn.setTitle(title, for: UIControl.State.normal)
            let color = self == self.navigationController?.viewControllers[0] ? UIColor.black : UIColor.white
            btn.setTitleColor(color, for: UIControl.State.normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        }
        
        if imageName.count > 0 {
           btn.setImage(UIImage(named: imageName), for: UIControl.State.normal)
        }
        
        
        self.navBar?.addSubview(btn)
    }
    
    //MARK:自定义导航栏右键
    /**
     * 自定义导航栏右键
     *
     * - Parameters:
     * - title: title
     * - titleColor: titleColor
     * - imageName: imageName
     * - width: btn的宽度  推荐 44 || 66 （两个字至四个字）
     * - customRightBtnClick: btn点击事件
     */
    func addNavRightButtonWithTitle(title:String, titleColor:UIColor, imageName:String, width:CGFloat, customRightBtnClick:(() -> ())?){
        
        for view in self.navBar?.subviews ?? [] {
            if view.n_left == MAINWIDTH - width {
                view.removeFromSuperview()
            }
        }
        
        self.customRightBtnClick = customRightBtnClick
        let btn = UIButton.init(type: UIButton.ButtonType.custom)
        btn.frame = CGRect(x: MAINWIDTH - width, y: StatusBarHeight, width: width, height: 44)
        btn.adjustsImageWhenDisabled = false
        btn.adjustsImageWhenHighlighted = false
        btn.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.right
        btn.addTarget(self, action: #selector(rightOrLeftOrSearchClick(sender:)), for: UIControl.Event.touchUpInside)
        btn.tag = 2
        if title.count != 0 {
            btn.setTitle(title, for: UIControl.State.normal)
            let color = self == self.navigationController?.viewControllers[0] ? UIColor.black : titleColor
            btn.setTitleColor(color, for: UIControl.State.normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        }
        btn.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 10)
        btn.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 20)
        btn.setImage(UIImage(named: imageName), for: UIControl.State.normal)
        navRightBtn = btn
        self.navBar?.addSubview(navRightBtn ?? UIButton())
        
    }
    
    //MARK:自定义搜索TF导航栏
    /**
     * 自定义搜索导航栏
     *
     * - Parameters:
     * - title: title
     * - imageName: imageName
     * - customRightBtnClick: btn点击事件
     */
    func addNavSearchTFWithPlaceholder(title:String,searchTitle:String, customSearchAction:((_ searchStr:String) -> ())?){
        
        for view in (self.navBar?.subviews)! {
            view.removeFromSuperview()
        }
        self.customSearchAction = customSearchAction
        let backView = UIView.init(frame: CGRect(x: 0, y: StatusBarHeight, width: MAINWIDTH, height: 44))
        backView.backgroundColor = UIColor.white
        backView.setShadow(width: MAINWIDTH, bColor: UIColor.clear, sColor: UIColor.hexInt(0xd2d2d2), offset: CGSize(width: 0, height: 5), opacity: 0.3, radius: 2.5)
        let cancelBtn = UIButton.init(frame: CGRect(x: MAINWIDTH - 44, y: 0, width: 44, height: 44))
        cancelBtn.setTitle("取消", for: UIControl.State.normal)
        cancelBtn.setTitleColor(UIColor.hexInt(0x46464A), for: UIControl.State.normal)
        cancelBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        cancelBtn.addTarget(self, action: #selector(backAction), for: UIControl.Event.touchUpInside)
        backView.addSubview(cancelBtn)
        let searchBackView = UIView.init(frame: CGRect(x: 10, y: 5, width: MAINWIDTH - 54, height: 30))
        searchBackView.backgroundColor = UIColor.hexInt(0xf4f4f4)
        searchBackView.clicpCorner(cornorRadius: 17)
        backView.addSubview(searchBackView)
        let searchImg = UIImageView.init(frame: CGRect(x: 10, y: 5, width: 20, height: 20))
        searchImg.image = UIImage(named: "nav_search")
        //        searchImg.theme_image = "Image.nav_search"
        searchBackView.addSubview(searchImg)
        let searchTF = UITextField.init(frame: CGRect(x: 33, y: 0, width: searchBackView.n_width - 38, height: 30))
        searchTF.placeholder = title
        searchTF.text = searchTitle
        searchTF.font = UIFont.systemFont(ofSize: 15)
        searchTF.tintColor = mainGreenColor//设置光标颜色
        searchTF.delegate = self
        searchTF.returnKeyType = UIReturnKeyType.search
        searchBackView.addSubview(searchTF)
        self.searchTF = searchTF
        self.navBar?.addSubview(backView)
    }
    
    //MARK:自定义导航栏 左、右、搜索按钮响应x事件
    @objc func rightOrLeftOrSearchClick(sender:UIButton) {
        
        switch sender.tag {
        case 1:
            
            if self.customleftBtnClick != nil {
                self.customleftBtnClick!()
            }
            
            break
        case 2:
            
            if self.customRightBtnClick != nil {
                self.customRightBtnClick!()
            }
            
            break
        default:
            break
        }
    }
    
    //MARK:上下拉刷新
    func setRefresh(scrollView:UIScrollView) {
        
        self.setMJHeader(scrollView: scrollView)
        self.setMJFooter(scrollView: scrollView)
        self.refreshScrollView = scrollView
    }
    
    func setMJHeader(scrollView:UIScrollView) {
        mjHeader.setRefreshingTarget(self, refreshingAction: #selector(refreshData))
        mjHeader.lastUpdatedTimeLabel.isHidden = true
        scrollView.mj_header = nil
        scrollView.mj_header = mjHeader
    }
    
    func setMJFooter(scrollView:UIScrollView) {
        mjFooter.setRefreshingTarget(self, refreshingAction: #selector(loadMoreData))
        scrollView.mj_footer = nil
        scrollView.mj_footer = mjFooter
    }
    
    
    func removeMJRefresh(scrollView:UIScrollView) {
        scrollView.mj_header = nil
        scrollView.mj_footer = nil
    }
    
    @objc func refreshData() {
        
        self.page = 1;
        self.loadData()
        self.refreshScrollView!.mj_header.endRefreshing()
        self.refreshScrollView!.mj_footer.endRefreshing()//解决为NoMoreData时候无法再上拉加载
        
    }
    
    @objc func loadMoreData() {
        
        self.page += 1
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.1) {
            if self.page > self.totalPage {
                self.refreshScrollView!.mj_footer.endRefreshingWithNoMoreData()
            }else{
                self.loadData()
                self.refreshScrollView!.mj_footer.endRefreshing()
            }
        }
    }
    
    //MARK:数据加载
    func loadData() {
        
    }

}

extension BaseViewController:UITextFieldDelegate {
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        
        if textField.text == "" {
            LYProgressHUD.showMessage("请输入搜索关键字")
            return false
        }
        
        if self.customSearchAction != nil {
            self.customSearchAction!(textField.text ?? "")
        }
        return true
    }
}


//MARK:tableView delegate、dataSource
extension BaseViewController: UITableViewDelegate , UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 0
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view:UIView = UIView(frame: CGRect(x: 0, y: 0, width: MAINWIDTH, height: 0))
        view.backgroundColor = UIColor.clear
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view:UIView = UIView(frame: CGRect(x: 0, y: 0, width: MAINWIDTH, height: 0))
        view.backgroundColor = UIColor.clear
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        
        return UITableViewCell.EditingStyle.none
    }
    
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        
        return "删除"
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        
        if editingStyle == UITableViewCell.EditingStyle.delete {
            
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
    }
    
    func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
        
        
    }
    
}

//MARK:collectionView delegate、dataSource、layoutDelegate
extension BaseViewController:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let reusableView = UICollectionReusableView()
        return reusableView
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        return CGSize(width: 0, height: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize(width: 0, height: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize.init(width: 0, height: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = UICollectionViewCell()
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
    }
}
